package com.papers.juan.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.UUID;

public class FileUtil {

	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}

	public static String createDateStr() {
		Calendar instance = Calendar.getInstance();
		Integer month = instance.get(instance.MONTH) + 1;
		return instance.get(instance.YEAR) + "/" + month + "/" + instance.get(instance.DAY_OF_MONTH) + "/";
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}

	/**
	 * 获取文件后缀
	 *
	 * @param fileName
	 * @return
	 */
	public static String getFileSuffix(String fileName) {
		if (fileName.indexOf(".") > -1) {
			return fileName.substring(fileName.lastIndexOf(".") + 1);
		}
		return "";
	}

	public static String getFileNameNoSurffix(String fileName) {
		if (fileName.indexOf(".") > -1) {
			return fileName.substring(0, fileName.lastIndexOf("."));
		}
		return fileName;
	}

	/**
	 * 下载文件
	 *
	 * @param response
	 * @param path
	 */
	public static void download(HttpServletResponse response, String path, String fileName) {
		System.out.println("下载文件=====================================");
		System.out.println(path);
		System.out.println("=====================================");
		File file = new File(path);
		try (
			FileInputStream inputStream = new FileInputStream(file);
			OutputStream outputStream = response.getOutputStream();
		) {
			response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("utf-8"), "ISO_8859_1"));
			byte[] b = new byte[1024];
			int len;
			while ((len = inputStream.read(b)) > 0) {
				outputStream.write(b, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
